package export

import (
	"bufio"
	"encoding/json"
	"fmt"
	"game/game-design-v.xnanz/loader"
	"os"
	"strconv"
	"strings"
)

type TextJsonIO struct {
}

func (c *TextJsonIO) Read(fileFullName string) ([]*loader.DesignFile, error) {
	var designFiles []*loader.DesignFile = make([]*loader.DesignFile, 0)
	file0, err := os.Open(fileFullName)
	if err != nil {
		fmt.Println(err)
		return designFiles, err
	}
	//TODO 修改读表

	var builder strings.Builder
	scanner := bufio.NewScanner(file0)
	for scanner.Scan() {
		line := scanner.Text()
		builder.WriteString(line)
	}

	var rows [][]string = make([][]string, 0)
	json.Unmarshal([]byte(builder.String()), &rows)

	fileInfo, err := os.Stat(fileFullName)
	if err != nil {
		fmt.Println("Error getting file info:", err)
		return designFiles, err
	}
	dFile := loader.NewDesignFile(fileInfo.Name(), rows)
	designFiles = append(designFiles, dFile)
	return designFiles, nil
}

func (c *TextJsonIO) Write(designFile *loader.DesignFile, exportFor *ExportFor) {
	os.Mkdir(exportFor.OutputFolder, 0755)
	if !designFile.FileNeedExport(exportFor.Tags) {
		fmt.Println("导出忽略", exportFor.Tags, designFile.Name)
		return
	}
	file, err := os.OpenFile(fmt.Sprintf("%s%s.json", exportFor.OutputFolder, designFile.GetOutputName()), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println("导出异常", exportFor.Tags, designFile.Name, err)
		return
	}
	defer file.Close()

	file.WriteString("[")

	marcos := make([]string, 0)
	marcos = append(marcos, designFile.Macros...)

	names := make([]string, 0, len(designFile.Fields))
	types := make([]string, 0, len(designFile.Fields))
	tags := make([]string, 0, len(designFile.Fields))
	comments := make([]string, 0, len(designFile.Fields))

	for _, field := range designFile.Fields {
		needExport := loader.FieldNeedExport(field.FieldTags, exportFor.Tags)
		if !needExport {
			continue
		}
		names = append(names, field.FieldName)
		types = append(types, field.FieldType)
		tags = append(tags, strings.Join(field.FieldTags, ","))
		comments = append(comments, field.FieldComment)
	}

	fieldLines := make([][]string, 5)
	fieldLines[0] = marcos
	fieldLines[designFile.NameRow] = names
	fieldLines[designFile.TypeRow] = types
	fieldLines[designFile.TagRow] = tags
	fieldLines[designFile.CommentRow] = comments

	for i, v := range fieldLines {
		data, _ := json.Marshal(v)
		if i != 0 {
			file.WriteString(",")
		}
		file.WriteString("\n" + string(data))
	}

	for _, data := range designFile.Datas {
		var jsonArray []interface{} = make([]interface{}, 0, len(data))

		for i, field := range designFile.Fields {
			needExport := loader.FieldNeedExport(field.FieldTags, exportFor.Tags)
			if !needExport {
				continue
			}
			var value string = ""
			if i >= len(data) {
				value = ""
			} else {
				value = data[i]
			}
			num, err := strconv.ParseInt(value, 10, 64)
			if err == nil {
				jsonArray = append(jsonArray, num)
			} else {
				num, err := strconv.ParseFloat(value, 64)
				if err == nil {
					jsonArray = append(jsonArray, num)
				} else {
					jsonArray = append(jsonArray, value)
				}
			}
		}
		data, _ := json.Marshal(jsonArray)
		file.WriteString(",")
		file.WriteString("\n" + string(data))
	}
	file.WriteString("\n]")
	fmt.Println("导出成功", exportFor.Tags, designFile.Name)
}
